import { getPicCode, getCode } from '@/api/login';

export default (await import('vue')).defineComponent({
  name: 'loginIndex',
  data () {
    return {
      picCode: '',
      phone: '',
      picBase64: '',
      picKey: '',
      totalSecond: 5,
      currentSecond: 5,
      timer: null // 定时器
    };
  },
  created () {
    this.getPicCode();
  },

  methods: {
    // 校验格式
    correct () {
      if (!/^1[3-9]\d{9}$/.test(this.phone)) {
        this.$toast('请输入正确的手机号');
        return false;
      }
      if (!/^\w{4}$/.test(this.picCode)) {
        this.$toast('请输入正确的图形验证码');
        return false;
      }
      return true;
    },

    // 获得图形验证码
    async getPicCode () {
      const { data: { base64, key } } = await getPicCode();
      this.picBase64 = base64,
        this.picKey = key;
      this.$toast('获得图形验证码成功');

    },

    // 获得短信验证码
    async getCode () {
      // 校验书写合法
      if (!this.correct()) {
        return;
      }

      /*
      已经放到统一拦截器处理，只要是非200的直接抛出错误
       
      // (已解决)有bug：无论验证码是否符合都发送成功
      // 请求验证码
      const code = await getCode(this.picCode, this.picKey, this.phone)
      console.log(code);
       
      // 校验code是否正确
      if (code.status === 500) {
      this.$toast(code.message)
      return
      }
       
      */
      // 进入倒计时
      if (!this.timer && this.totalSecond === this.currentSecond) {

        await getCode(this.picCode, this.picKey, this.phone);

        this.timer = setInterval(() => {
          this.currentSecond--;
          if (this.currentSecond <= 0) {
            clearInterval(this.timer);
            this.timer = null;
            this.currentSecond = this.totalSecond;
          }
        }, 1000);
        this.$toast('发送成功，请注意查收');
      }

    }
  }
});
